<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>web worker</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
    <p>这是web worker</p>
    <h1>专用线程 --- </h1>
    <br><br>
     <canvas id="oldCanvas" width="500px" height="300px"> 
     </canvas> 
     <canvas id="nowCanvas" width="500px" height="300px"> 
     </canvas> 
        <br>
      <button onclick = "reminiscence_Filter()">怀旧滤镜</button><br>
      <button onclick = "copy10()">青色滤镜</button><br> 
</body>
<script>
    console.log(window.Worker)
    //为了更好的错误处理控制以及向下兼容，将你的worker运行代码包裹在以下代码中是一个很好的想法
    if(!window.Worker){  
        alert("您的浏览器不支持Web Worker!,请升级或更换浏览器")
    }
    var jsFileURI = 'task.js';

    //生成一个专用worker
    //创建一个新的worker很简单。你需要做的是调用Worker() 的构造器，指定一个脚本的URI来执行worker线程
    //同域限制
    //worker在访问时, 只能是在同一host下才行. 即, 你的worker只能处于指定目录下的path中。
    var worker = new Worker(jsFileURI);

    //专用worker中消息的接收和发送workers的方法通过postMessage() 方法和onmessage事件处理函数生效。
    // worker.postMessage('加工我吧??快来吧??');
    worker.onmessage = function (e) {
        var timer2 = (new Date()).valueOf();
        console.log( '结果：'+event.data, '时间:'+ timer2, '用时：'+ ( timer2  - timer ) );
    };


    var timer = (new Date()).valueOf();
    console.log('开始计算：40','时间:'+ timer );

    //终止worker
    //worker.terminate();
    //
    worker.postMessage(40);
    console.log('我在计算数列的时候执行了', '时间:'+ (new Date()).valueOf() );

    //处理错误
    worker.onerror = function(e){
        console.log('出错行数在:' + e.lineno + '行,错误是:'+ e.message +".")
    }

     //获取到canvas元素 
    var oldcanvas = document.getElementById('oldCanvas'); 
    //获取canvas中的画图环境 
    var oldcontext = oldcanvas.getContext('2d'); 
    //获取到canvas元素 
    var nowcanvas = document.getElementById('nowCanvas'); 
    //获取canvas中的画图环境 
    var nowcontext = nowcanvas.getContext('2d'); 
  
    var img = new Image(); 
    img.src = "./500647193.jpg"; 
  
    window.onload = function (){ 
      //绘制图像 
      oldcontext.drawImage(img,0,0,oldcanvas.width,oldcanvas.height);
    }; 
    
      var worker2 = new Worker('reminiscence_Filter.js');
       worker2.onmessage = function (e) {
        var imgdata2 = oldcontext.getImageData(0, 0, oldcanvas.width, oldcanvas.height); 
        imgdata2 = e.data
        nowcontext.putImageData(imgdata2,0,0); 
    };

   function reminiscence_Filter(){
    var imgdata = oldcontext.getImageData(0, 0, oldcanvas.width, oldcanvas.height); 
    worker2.postMessage({type:'复古',data:imgdata})
   }

   function copy10(){
    var imgdata = oldcontext.getImageData(0, 0, oldcanvas.width, oldcanvas.height); 
    worker2.postMessage({type:'青色',data:imgdata})
   }
</script>
</html>